<template>
  <div class="app-container">
    <el-card shadow="always">
      <el-form :model="queryParams" :inline="true" label-width="100px">
        <el-form-item label="标题：">
          <el-input v-model="queryParams.title" clearable placeholder="请输入标题；模糊匹配" style="width: 240px" />
        </el-form-item>
        <el-form-item label="提交人：">
          <el-input v-model="queryParams.creator" clearable placeholder="请输入提交人" style="width: 240px" />
        </el-form-item>
        <el-form-item label="审批状态：" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="dict in approveDic" :key="dict.value" :label="dict.label" :value="dict.value"
              :disabled="dict.flag" />
          </el-select>
        </el-form-item>
        <el-form-item label="审批人：" v-if="queryParams.type !== '1'">
          <!-- <el-input v-model="queryParams.approver" clearable placeholder="请输入审批人" style="width: 240px" /> -->
          <el-select v-model="queryParams.approver" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="dict in approvalUsersList" :key="dict" :label="dict" :value="dict" />
          </el-select>
        </el-form-item>
        <!--  <el-form-item label="提交时间：">
          <el-date-picker v-model="queryParams.createTime" type="daterange" placeholder="请选择时间" format="YYYY-MM-DD"
            value-format="YYYY-MM-DD" />
        </el-form-item> -->
        <el-form-item>
          <el-button type="primary" icon="Search" @click="getApproveList">查询</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="always" style="margin-top: 10px; min-height: 500px; padding-bottom: 20px">
      <el-row>
        <el-tabs style="height: 42px" v-model="queryParams.type" @tab-click="handleClick" type="card">
          <el-tab-pane label="待审核" name="1" v-if="limitFlag"></el-tab-pane>
          <el-tab-pane label="已审核" name="2" v-if="limitFlag"></el-tab-pane>
          <el-tab-pane label="我申请的" name="3"></el-tab-pane>
        </el-tabs>
      </el-row>
      <div id="table" style="margin-top: 12px">
        <el-table v-loading="loading" :data="tableData" style="width: 100%">
          <el-table-column prop="id" label="ID" width="100" align="center" />
          <el-table-column prop="title" label="标题" width="200" align="center" />
          <el-table-column prop="type" label="类型" width="150" align="center" />
          <el-table-column prop="status" label="审批状态" width="auto" align="center">
            <template #default="scope">
              <el-tag v-if="scope.row.status == '0'" type="warning">{{ getCurrntStatus('0') }}</el-tag>
              <el-tag v-if="scope.row.status == '1'" type="success">{{ getCurrntStatus('1') }}</el-tag>
              <el-tag @click="getFail(scope.row)" v-if="scope.row.status == '2'" type="danger"
                style="cursor: pointer;">{{ getCurrntStatus('2') }}</el-tag>
              <el-tag v-if="scope.row.status == '3'" type="danger">{{ getCurrntStatus('3') }}</el-tag>
              <el-tag v-if="scope.row.status == '4'" type="danger">{{ getCurrntStatus('4') }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="creator" label="提交人" width="120" align="center" />
          <el-table-column prop="createTime" label="提交时间" width="200" :formatter="dateFormatter" align="center" />
          <el-table-column prop="approver" label="审批人" v-if="queryParams.type != 1" width="120" align="center" />
          <el-table-column prop="updateTime" label="审批时间" v-if="queryParams.type != 1" :formatter="dateFormatter"
            width="200" align="center" />
          <el-table-column label="待审批人" width="auto" min-width="220" align="center" v-if="queryParams.type !== '2'">
            <template #default="scope">
              <el-tag style="margin-right: 3px;" v-if="scope.row.status == '0'" v-for="item in approvalUsersList">{{
                item }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="approver" label="审批人" v-if="queryParams.type != 1" width="120" align="center" />
          <el-table-column prop="updateTime" label="审批时间" v-if="queryParams.type != 1" width="200"
            :formatter="dateFormatter" align="center" />
          <el-table-column fixed="right" label="操作" align="center" min-width="200">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="setApprove(scope.row)"
                v-if="queryParams.type == 1">审批</el-button>
              <el-button v-if="scope.row.status === 1" link type="primary" size="small"
                @click="exportData(scope.row)">下载</el-button>
              <el-button link type="primary" size="small" @click="setApproveBack(scope.row)"
                v-if="queryParams.type == 3 && scope.row.status == 0">退回</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 50, 100, 200]"
          layout="total, sizes, prev, pager, next" :total="total" @size-change="getApproveList"
          @current-change="getApproveList" /> -->
        <pagination v-show="total > 0" :total="total" v-model:page="currentPage" v-model:limit="pageSize"
          @pagination="getApproveList" :autoScroll="false" />
      </div>
    </el-card>

    <approveDialog ref="refApproveDialog" @reflash="getApproveList" />

    <el-dialog width="550" v-model="showDialog" :close-on-click-modal="false" :modal-append-to-body="false"
      :close-on-press-escape="false">
      <template #header>
        <span>驳回原因</span>
      </template>
      <div class="container">
        您因<b style="margin: 0 10px;">{{ failReason }}</b>原因,审核不通过
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showDialog = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="download">
import {
  approveList,
  approveBack,
  approveReason
} from "@/api/biz/exportApi";
import tabledata from './tabledata.json'

import approveDialog from './approveDialog.vue'

import { useConfigStore } from '@/store/modules/config.js'  // store
import useUserStore from '@/store/modules/user'
import { disable } from "ol/rotationconstraint";
import { ElMessage } from 'element-plus'


const router = useRouter();

const { proxy } = getCurrentInstance();
const { sys_approve } = proxy.useDict(
  'sys_approve',
);

let approveDic = [{
  label: '待审核',
  value: '0',
  flag: false
}, {
  label: '已通过',
  value: '1',
  flag: true
}, {
  label: '已驳回',
  value: '2',
  flag: true
}, {
  label: '异常',
  value: '3',
  flag: true
}, {
  label: '已退回',
  value: '4',
  flag: true
}
]

let showDialog = ref(false)
let failReason = ref('xxx')

const userStoreData = useUserStore()
const configStoreData = useConfigStore()

const refApproveDialog = ref(null)

let activeName = ref('待审批')
let limitFlag = ref(false)  // 审批权限

let loading = ref(false)

const queryParams = ref({
  type: "",  // // 审批类型 - 待审批1、已审批2、我申请的3
});

const pageSize = ref(10);
const currentPage = ref(1);
const total = ref(0);
const tableData = ref([]);

let approvalUsersList = ref([])

const getCurrntStatus = (status) => {
  return approveDic.filter(item => item.value === status)[0]?.label
}

const getUserLimit = () => {
  let approvalUserConfig = configStoreData.configList.filter(item => item.configKey === 'sys.approval_user')[0]
  let approvalUsers = approvalUserConfig.configValue.split(';')
  approvalUsersList.value = approvalUsers

  const { userName } = userStoreData.userMseeage

  if (approvalUsers.includes(userName)) {
    limitFlag.value = true
    //默认展示
    queryParams.value.type = "1"
  } else {
    //普通用户
    queryParams.value.type = "3"
  }
}

const resetQuery = () => {
  queryParams.value = {
    type: "1",  // // 审批类型 - 待审批1、已审批2、我申请的3
  }

  getApproveList();
}

// 导出
function exportData(row) {
  const { id, filePath } = row
  let fileName = ''
  // console.log(id, filePath)

  if (filePath) {
    fileName = filePath.split(/[/\\]/).pop()
    console.log(fileName)
  } else {
    fileName = `导出数据_${new Date().getTime()}.csv`
  }

  proxy.download("/export/exportFile", { id }, fileName);
}

const getFail = (row) => {
  showDialog.value = true
  const { remark } = row
  console.log(remark)

  failReason.value = remark
}

const setApproveBack = (row) => {
  proxy.$modal.confirm('是否确认退回参数编号为"' + row.id + '"的数据项？').then(() => {
    approveBack({ id: row.id }).then(res => {
      ElMessage({
        message: '退回成功',
        type: 'success',
        plain: true,
      })
    })
    getApproveList()
  }).catch(() => { });
}

const handleClick = (tab) => {
  // type => 待审核1、已审核2、我申请的3
  // status => 待审核0、已通过1-2、已驳回3

  /**
   * 待审核
   * type 1, status 0
   * 
   * 已审核
   * type 2, status !== 0
   * 
   * 我申请的
   * type 3
   */

  const { props } = tab
  queryParams.value.type = props.name
  queryParams.value.status = ''

  if (props.name === '1') {
    approveDic[0].flag = false  // 待审核
    approveDic[1].flag = true  // 已通过
    approveDic[2].flag = true  // 已驳回
  }
  if (props.name === '2') {
    approveDic[0].flag = true  // 待审核
    approveDic[1].flag = false  // 已通过
    approveDic[2].flag = false  // 已驳回
  }
  if (props.name === '3') {
    approveDic[0].flag = false  // 待审核
    approveDic[1].flag = false  // 已通过
    approveDic[2].flag = false  // 已驳回
  }

  getApproveList()
}

function getApproveList() {
  let param = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    ...queryParams.value,
  };
  loading.value = true;
  approveList(param).then((res) => {
    console.log(res)
    tableData.value = res.rows;
    total.value = res.total;

    loading.value = false;
  });
}

function setApprove(row) {
  refApproveDialog.value.show(row)
}

function dateFormatter(row, column, cellValue, index) {
  if (!cellValue) { return }
  // 创建一个新的 Date 对象
  var originalDate = new Date(cellValue);
  // 获取年、月、日、时、分、秒
  var year = originalDate.getFullYear();
  var month = ("0" + (originalDate.getMonth() + 1)).slice(-2);
  var day = ("0" + originalDate.getDate()).slice(-2);
  var hours = ("0" + originalDate.getHours()).slice(-2);
  var minutes = ("0" + originalDate.getMinutes()).slice(-2);
  var seconds = ("0" + originalDate.getSeconds()).slice(-2);

  // 格式化输出
  var formattedDateTimeString = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
  return formattedDateTimeString;
}

getUserLimit();
getApproveList();
</script>
